/** 工具类函数，不允许业务相关 **/
export const useFunction = () => {
  const getSys = () => {
    return uni.getSystemInfoSync()
  }

  const getPosition = () => {
    if (!is_wx()) {
      return MapLoader({
        succes: (res) => {
          const { lat, lng } = res.position
          const url = lng + ',' + lat
          getPois(url)
        },
        error: (err) => {
          console.log(err)
        },
      })
    }
  }

  /** 判断是否在微信浏览器*/
  const is_wx = () => {
    const en = window.navigator.userAgent.toLowerCase()
    // 匹配en中是否含有MicroMessenger字符串
    const isWX = en.includes('micromessenger')

    // 微信内置浏览器
    return isWX

    //其他浏览器
    // return false
  }

  // 浏览器端获取位置
  const MapLoader = ({ succes = (data: any) => data, error = (data: any) => data }) => {
    const aMapScript = document.createElement('script')
    aMapScript.setAttribute(
      'src',
      'https://webapi.amap.com/maps?v=1.4.11&key=fff8ca443e24cedd40bf6e1ba2bcef33&plugin=AMap.CitySearch'
    )
    document.head.appendChild(aMapScript)
    return (aMapScript.onload = function () {
      AMap.plugin('AMap.Geolocation', function () {
        const geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: true,
          // 设置定位超时时间，默认：无穷大
          timeout: 10000,
          // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
          buttonOffset: new AMap.Pixel(10, 20),
          //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          zoomToAccuracy: true,
          //  定位按钮的排放位置,  RB表示右下
          buttonPosition: 'RB',
        })

        geolocation.getCurrentPosition()
        AMap.event.addListener(geolocation, 'complete', succes)
        AMap.event.addListener(geolocation, 'error', error)
      })
    })
  }

  const windowPosition = () => {
    console.log(navigator.geolocation)

    navigator.geolocation.getCurrentPosition(
      (position) => {
        console.log('latitude', position.coords.latitude)
        console.log(position.coords.longitude)
      },
      (err) => {
        console.log(err)
      }
    )
  }

  const getPois = async (location = '120.21034,30.187676', page = 1) => {
    const res = await fetch(
      `https://restapi.amap.com/v3/place/around?key=6ec8fc73a8c36a90740a4b8f644356b5&location=${location}&radius=10000&types=餐饮服务&page=${page}&offset=10`
    )

    const data = await res.json()
    return data
  }

  return {
    getSys,
    MapLoader,
    is_wx,
    getPosition,
    getPois,
    windowPosition,
  }
}
